package com.hu.bgp.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import com.hu.bgp.client.widgets.GameTypeTableAdmin;
import com.hu.bgp.framework.util.FailureHandler;
import com.hu.bgp.framework.util.FailureHandlingCallback;
import com.hu.bgp.shared.AdminService;
import com.hu.bgp.shared.AdminServiceAsync;
import com.hu.bgp.shared.ClientGameType;
import com.hu.bgp.shared.ClientGameTypeCollection;

/**
 * De GUI voor admins
 * 
 * @author ejvos
 */
public class AdminClient implements EntryPoint, FailureHandler
{
	private AdminServiceAsync adminService;
	private final Button loadButton = new Button("Load selected game type");
	private final Button unloadButton = new Button("Unload selected game type");
	private final GameTypeTableAdmin gameTypeTableAdmin = new GameTypeTableAdmin();

	public void onModuleLoad()
	{
		// get a binding to the servlet
		adminService = GWT.create(AdminService.class);
		ServiceDefTarget target = (ServiceDefTarget) adminService;
		// zie ook BgpConfiguration.getPlayerClientUrlPrefix
		target.setServiceEntryPoint("/bgp/adminService");

		ClickHandler clickHandler = new ClickHandler()
		{
			public void onClick(ClickEvent event)
			{
				boolean activate = event.getSource() == loadButton;
				adminService.setGameTypeActivation(gameTypeTableAdmin.getSelection(), activate, new FailureHandlingCallback<Void>(AdminClient.this)
				{
					public void onSuccess(Void result)
					{
						Window.alert("Succes!");
						loadAdminEntries();
					}
				});
			}
		};
		loadButton.addClickHandler(clickHandler);
		unloadButton.addClickHandler(clickHandler);

		loadAdminEntries();

		RootPanel gameTypeTable = RootPanel.get("gameTypeTable");
		RootPanel actionButtons = RootPanel.get("actionButtons");
		gameTypeTable.getElement().setInnerText("");
		actionButtons.getElement().setInnerText("");
		gameTypeTable.add(gameTypeTableAdmin);

		loadButton.setStyleName("displayInline");
		unloadButton.setStyleName("displayInline");
		actionButtons.add(loadButton);
		actionButtons.add(unloadButton);
	}

	// TODO QUICK DIRTY HACK
	private void loadAdminEntries()
	{
		gameTypeTableAdmin.clear();
		adminService.getClientGameTypeAdminCollection(new FailureHandlingCallback<ClientGameTypeCollection>(this)
		{
			public void onSuccess(ClientGameTypeCollection result)
			{
				for (ClientGameType gameType : result)
				{
					gameTypeTableAdmin.addGameRow(gameType);
				}
			}
		});
	}

	public void onFailure(Throwable caught)
	{
		caught.printStackTrace();
	}
}
